﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WLYT.Repository;

namespace WLYT.Application.Services
{
    public class BaseService<T> where T : class, new()
    {
        protected readonly ISqlSugarRepository<T> _baseRepository;

        public BaseService(ISqlSugarRepository<T> _baseRepository)
        {
            this._baseRepository = _baseRepository;
        }

        public async Task<bool> AddAsync(T entity)
        {
            return await _baseRepository.InsertAsync(entity);
        }

        public async Task<bool> DeleteAsync(int id)
        {
            return await _baseRepository.DeleteByIdAsync(id);
        }

        public async Task<bool> DeleteAsync(string ids)
        {
            return await DeleteAsync(ids.Split(','));
        }

        public async Task<bool> DeleteAsync(string[] ids)
        {
            return await _baseRepository.DeleteByIdsAsync(ids);
        }

        public async Task<bool> UpdateAsync(T entity)
        {
            return await _baseRepository.UpdateAsync(entity);
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await _baseRepository.GetByIdAsync(id);
        }

        public Task<Tuple<IList<T>, int>> GetPageListAsync(Expressionable<T> whereExpression, int pageSize, int pageIndex, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Desc)
        {
            return GetPageListAsync(whereExpression.ToExpression(), pageSize, pageIndex, orderByExpression, orderByType);
        }

        public async Task<Tuple<IList<T>, int>> GetPageListAsync(Expression<Func<T, bool>> whereExpression, int pageSize, int pageIndex, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Desc)
        {
            var pageModel = new PageModel { PageIndex = pageIndex, PageSize = pageSize };
            var result = await _baseRepository.GetPageListAsync(whereExpression, pageModel, orderByExpression, orderByType);
            return new Tuple<IList<T>, int>(result, pageModel.TotalCount);
        }

        public async Task<Tuple<IList<T>, int>> GetPageListAsync(List<IConditionalModel> conditionalList, int pageSize, int pageIndex, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Desc)
        {
            var pageModel = new PageModel { PageIndex = pageIndex, PageSize = pageSize };
            var result = await _baseRepository.GetPageListAsync(conditionalList, pageModel, orderByExpression, orderByType);
            return new Tuple<IList<T>, int>(result, pageModel.TotalCount);
        }
    }
}
